/*
 * 文件名：UploadPlatformThread.java	 
 * 时     间：下午5:38:47
 * 作     者：Administrator       
 * 版     权： 2012-2022 湖南智软网络科技, 公司保留所有权利.
 * 联     系：http://www.073586.com/
 */
package com.local.manager.thread;

import java.io.IOException;
import java.util.Date;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;

import com.cloud.entity.ResultVo;
import com.cz073586.tools.http.HttpManagerUtil;
import com.cz073586.tools.util.JsonUtil;
import com.cz073586.tools.util.Log4jUtil;
import com.cz073586.tools.util.Tools;
import com.local.common.LogInfoConstan;
import com.local.entity.vo.ParkwellPayBillVo;
import com.local.entity.vo.PayCarVo;
import com.local.manager.cfgManager.CloudConfigManager;
import com.local.model.CarParkOut;
import com.local.model.LocalCouponCash;
import com.local.model.LocalPayBill;
import com.local.model.Log;
import com.local.service.face.LogService;
import com.local.util.HttpClientUtil;

/**
 * 类描述:这里是类描述
 * 
 * @ClassName: UploadPlatformThread
 * @author Administrator
 * @date 2016年3月25日 下午5:38:47
 */
public class UploadPlatformThread implements Runnable
{
	
	private Log4jUtil log = Log4jUtil.getLog4j(UploadPlatformThread.class);
	private CarParkOut carParkOut;
	private LogService logServier;
	private ParkwellPayBillVo parkwellPayBillVo;
	
	
	
	public UploadPlatformThread(CarParkOut carParkOut, LogService logServier,
			ParkwellPayBillVo parkwellPayBillVo)
	{
		super();
		this.carParkOut = carParkOut;
		this.logServier = logServier;
		this.parkwellPayBillVo = parkwellPayBillVo;
	}

	@Override
	public void run()
	{
		// 如果开启了云平台
		if (CloudConfigManager.instance().isOpen())
		{
			//上传出场记录到云平台
			this.upLoadCarOutInfo();
			
			// 更新出场记录到云平台
			this.upDateCarOutInfo();
			
			if (parkwellPayBillVo.isAuotPayOut())
			{
				
				// 更新百事通自动扣费信息
				this.uploadCarPayInfo();
			}
			if (!Tools.isEmpty(parkwellPayBillVo.getPayBill()))
			{
				// 更新流水到云平台
				this.uploadPayBill(parkwellPayBillVo.getPayBill());
			}
			
			// 生成的流水，同步到云平台
			for (LocalPayBill cnpBill : parkwellPayBillVo
					.getCouponToPayBillsList())
			{
				// 更新流水到云平台
				this.uploadPayBill(cnpBill);
			}
			
			// 使用的商家抵用劵记录，上传到云系统，并修改使用状态
			for (LocalCouponCash lc : parkwellPayBillVo.getLscList())
			{
				this.upDateCouponCash(lc);
			}
		}
	}
	
	// 更新出场记录到云平台
	private void upDateCarOutInfo()
	{
		
		// 发送请求
		CloseableHttpClient httpClient = HttpManagerUtil.getInstance()
				.getHttpClient(null);
		try
		{
			
			if (Tools.isEmpty(this.carParkOut))
			{
				return;
			}
			// 获取请求路径
			String uri = CloudConfigManager.instance().getHost()
					+ CloudConfigManager.instance().getCfgValueByKey(
							"sync_car_out_update");
			
			HttpPost post = new HttpPost(uri);
			post.setHeader("Content-Type", "application/json;charset=UTF-8");
			post.setConfig(HttpClientUtil.getTimeOutCfg(0));
			String sendData = JsonUtil.getJsonString(this.carParkOut);
			StringEntity s = new StringEntity(sendData, "UTF-8");
			post.setEntity(s);
			
			CloseableHttpResponse resp = httpClient.execute(post);
			String result = EntityUtils.toString(resp.getEntity(), "UTF-8");
			
			ResultVo resultVo = (ResultVo) JsonUtil.getObjectByJson(result,
					ResultVo.class);
			
			if (Tools.isEmpty(resultVo))
			{
				System.out.println(this.carParkOut.getCarNo() + "云平台返回空.");
			}
			
			if (resultVo.getResult().equals("success"))
			{
				System.out.println(this.carParkOut.getCarNo() + ",更新出场纪录成功..");
				// this.logServier.deleteCarInfoAndPayBill(this.carParkOut);
			} else
			{
				System.out.println(this.carParkOut.getCarNo() + ",更新出场纪录失败.");
				System.out.println(resultVo.getErrorMsg());
				addErrorLog(this.carParkOut.getUuid(), "更新出场纪录失败.");
			}
			
		} catch (Throwable t)
		{
			this.log.error("", t);
			addErrorLog(this.carParkOut.getUuid(), "更新出场纪录失败.");
			try
			{
				if (httpClient != null)
				{
					httpClient.close();
				}
			} catch (IOException localIOException1)
			{
			}
		} finally
		{
			try
			{
				if (httpClient != null)
				{
					httpClient.close();
				}
			} catch (IOException localIOException2)
			{
				
			}
		}
	}
	
	public void addErrorLog(String businessUuid, String deScript)
	{
		Log logInfo = new Log();
		logInfo.setCreaterAt(new Date());
		logInfo.setSummary("更新出场信息异常.");
		logInfo.setDescript(deScript);
		logInfo.setLevel("警告");
		logInfo.setSrc("系统");
		logInfo.setStatus(Integer.valueOf(1));
		logInfo.setCls("com.cloud.threads.UpDateCarOutInfoRunble");
		logInfo.setModule(Integer.valueOf(3));
		logInfo.setBusinessUuid(businessUuid);
		this.logServier.addLogInfo(logInfo);
		
	}
	
	// 更新百事通自动扣费信息
	private void uploadCarPayInfo()
	{
		
		// 发送请求
		CloseableHttpClient httpClient = HttpManagerUtil.getInstance()
				.getHttpClient(null);
		try
		{
			if (Tools.isEmpty(this.parkwellPayBillVo))
			{
				return;
			}
			// 获取请求路径
			String uri = CloudConfigManager.instance().getHost()
					+ CloudConfigManager.instance().getCfgValueByKey(
							"sync_pay_car");
			
			HttpPost post = new HttpPost(uri);
			post.setHeader("Content-Type", "application/json;charset=UTF-8");
			post.setConfig(HttpClientUtil.getTimeOutCfg(0));
			PayCarVo payCarVo = new PayCarVo();
			
			if (Tools.isEmpty(parkwellPayBillVo.getExchangeUuid()))
			{
				parkwellPayBillVo.setExchangeUuid(CloudConfigManager.instance()
						.getCfgValueByKey("exchange_id"));
			}
			
			payCarVo.setParkId(parkwellPayBillVo.getExchangeUuid());
			payCarVo.setCarNum(parkwellPayBillVo.getCarNo());
			payCarVo.setCarParkInId(parkwellPayBillVo.getCarInUuid());
			payCarVo.setCoupon(parkwellPayBillVo.getCoupon());
			payCarVo.setInTime(parkwellPayBillVo.getCarInTime().getTime());
			// payCarVo.setMoney(parkwellPayBillVo.getTheoryPrice());
			// 通知自动扣费金额
			double mony = !Tools
					.isEmpty(parkwellPayBillVo.getPriceDifference()) ? parkwellPayBillVo
					.getPriceDifference() * 10 : 0d;
			payCarVo.setMoney((int) mony);
			
			String sendData = JsonUtil.getJsonString(payCarVo);
			StringEntity s = new StringEntity(sendData, "UTF-8");
			post.setEntity(s);
			
			CloseableHttpResponse resp = httpClient.execute(post);
			String result = EntityUtils.toString(resp.getEntity(), "UTF-8");
			
			ResultVo resultVo = (ResultVo) JsonUtil.getObjectByJson(result,
					ResultVo.class);
			
			if (resultVo.getResult().equals("success"))
			{
				System.out.println("百事通通自动扣费成功.");
			} else
			{
				System.out.println("百事通通自动扣费失败.");
			}
			
		} catch (Throwable t)
		{
			log.error("", t);
			try
			{
				if (httpClient != null)
				{
					httpClient.close();
				}
			} catch (IOException localIOException1)
			{
			}
		} finally
		{
			try
			{
				if (null != httpClient)
				{
					httpClient.close();
				}
			} catch (IOException e)
			{
			}
		}
	}
	
	// 更新流水到云平台
	private void uploadPayBill(LocalPayBill parkwellPayBill)
	{
		// 发送请求
		CloseableHttpClient httpClient = HttpManagerUtil.getInstance()
				.getHttpClient(null);
		try
		{
			// 获取请求路径
			String uri = CloudConfigManager.instance().getHost()
					+ CloudConfigManager.instance().getCfgValueByKey(
							"sync_pay_bill");
			
			HttpPost post = new HttpPost(uri);
			post.setHeader("Content-Type", "application/json;charset=UTF-8");
			post.setConfig(HttpClientUtil.getTimeOutCfg(0));
			
			// 获取系统当前停车场编号。
			parkwellPayBill.setExchangeUuid(CloudConfigManager.instance()
					.getExchangeId());
			
			String sendData = JsonUtil.getJsonString(parkwellPayBill);
			StringEntity s = new StringEntity(sendData, "UTF-8");
			post.setEntity(s);
			
			log.debug("上传支付流水纪录[信息].." + sendData);
			
			CloseableHttpResponse resp = httpClient.execute(post);
			String result = EntityUtils.toString(resp.getEntity(), "UTF-8");
			
			log.debug("上传支付流水纪录[返回].." + result);
			
			ResultVo resultVo = (ResultVo) JsonUtil.getObjectByJson(result,
					ResultVo.class);
			
			if (resultVo.getResult().equals("success"))
			{
				System.out.println("上传支付流水纪录成功..");
			} else
			{
				System.out.println("上传支付流水纪录失败.");
				addErrorPayBillLog(parkwellPayBill.getPayBillUuid(),
						"上传支付流水纪录失败.");
			}
			
		} catch (Throwable t)
		{
			log.error("", t);
			addErrorPayBillLog(parkwellPayBill.getPayBillUuid(), "上传支付流水纪录失败.");
			try
			{
				if (httpClient != null)
				{
					httpClient.close();
				}
			} catch (IOException localIOException1)
			{
			}
		} finally
		{
			try
			{
				if (null != httpClient)
				{
					httpClient.close();
				}
			} catch (IOException e)
			{
			}
		}
	}
	
	public void addErrorPayBillLog(String businessUuid, String deScript)
	{
		Log logInfo = new Log();
		logInfo.setCreaterAt(new Date());
		logInfo.setSummary("上传流水信息异常");
		logInfo.setDescript(deScript);
		logInfo.setLevel(LogInfoConstan.LEVEL_ALERT);
		logInfo.setSrc(LogInfoConstan.SRC_SYSTEM);
		logInfo.setStatus(LogInfoConstan.STATUS_UNTREATED);
		logInfo.setCls("com.cloud.threads.UploadPayBillRunble");
		logInfo.setModule(LogInfoConstan.MODULE_PAYBILL);
		logInfo.setBusinessUuid(businessUuid);
		logServier.addLogInfo(logInfo);
	}
	
	// 使用的商家抵用劵记录，上传到云系统，并修改使用状态
	private void upDateCouponCash(LocalCouponCash localCouponCash)
	{
		// 发送请求
		CloseableHttpClient httpClient = HttpManagerUtil.getInstance()
				.getHttpClient(null);
		try
		{
			if (Tools.isEmpty(localCouponCash))
			{
				return;
			}
			// 获取请求路径
			String uri = CloudConfigManager.instance().getHost()
					+ CloudConfigManager.instance().getCfgValueByKey(
							"sync_coupon_cash_update");
			
			HttpPost post = new HttpPost(uri);
			post.setHeader("Content-Type", "application/json;charset=UTF-8");
			post.setConfig(HttpClientUtil.getTimeOutCfg(0));
			String sendData = JsonUtil.getJsonString(localCouponCash);
			StringEntity s = new StringEntity(sendData, "UTF-8");
			post.setEntity(s);
			
			CloseableHttpResponse resp = httpClient.execute(post);
			String result = EntityUtils.toString(resp.getEntity(), "UTF-8");
			
			ResultVo resultVo = (ResultVo) JsonUtil.getObjectByJson(result,
					ResultVo.class);
			
			if (resultVo.getResult().equals("success"))
			{
				System.out.println("上传商家抵用劵修改纪录..");
			} else
			{
				System.out.println("上传商家抵用劵修改纪录失败.");
				addCouponErrorLog(localCouponCash.getCouponId(),
						"上传商家抵用劵修改纪录失败.");
			}
			
		} catch (Throwable t)
		{
			log.error("", t);
			addCouponErrorLog(localCouponCash.getCouponId(),
					"上传商家抵用劵修改纪录失败.");
			try
			{
				if (httpClient != null)
				{
					httpClient.close();
				}
			} catch (IOException localIOException1)
			{
			}
		} finally
		{
			try
			{
				if (httpClient != null)
				{
					httpClient.close();
				}
			} catch (IOException localIOException2)
			{
			}
		}
	}
	
	public void addCouponErrorLog(String businessUuid, String deScript)
	{
		Log logInfo = new Log();
		logInfo.setCreaterAt(new Date());
		logInfo.setSummary("修改抵用卷异常.");
		logInfo.setDescript(deScript);
		logInfo.setLevel("警告");
		logInfo.setSrc("系统");
		logInfo.setStatus(Integer.valueOf(1));
		logInfo.setCls("com.cloud.threads.UpDateCouponCashRunble");
		logInfo.setModule(Integer.valueOf(15));
		logInfo.setBusinessUuid(businessUuid);
		this.logServier.addLogInfo(logInfo);
		
	}
	
	// 上报车辆信息到云平台
	private void upLoadCarOutInfo()
	{
		
		// 发送请求
		CloseableHttpClient httpClient = HttpManagerUtil.getInstance()
				.getHttpClient(null);
		try
		{
			
			if (Tools.isEmpty(this.carParkOut))
			{
				return;
			}
			// 获取请求路径
			String uri = CloudConfigManager.instance().getHost()
					+ CloudConfigManager.instance().getCfgValueByKey(
							"sync_car_out");
			
			HttpPost post = new HttpPost(uri);
			post.setHeader("Content-Type", "application/json;charset=UTF-8");
			post.setConfig(HttpClientUtil.getTimeOutCfg(0));
			String sendData = JsonUtil.getJsonString(carParkOut);
			StringEntity s = new StringEntity(sendData, "UTF-8");
			post.setEntity(s);
			
			CloseableHttpResponse resp = httpClient.execute(post);
			String result = EntityUtils.toString(resp.getEntity(), "UTF-8");
			
			ResultVo resultVo = (ResultVo) JsonUtil.getObjectByJson(result,
					ResultVo.class);
			
			if (resultVo.getResult().equals("success"))
			{
				System.out.println(carParkOut.getCarNo() + "，上传出场纪录成功..");
			} else
			{
				System.out.println(carParkOut.getCarNo() + "，上传出场纪录失败.");
				System.out.println(resultVo.getErrorMsg());
				addUploadCarOutErrorLog(carParkOut.getUuid(), "，上传出场纪录失败.");
			}
			
		} catch (Throwable t)
		{
			log.error("", t);
			addUploadCarOutErrorLog(carParkOut.getUuid(), "，上传出场纪录失败.");
			try
			{
				if (httpClient != null)
				{
					httpClient.close();
				}
			} catch (IOException localIOException1)
			{
			}
		} finally
		{
			try
			{
				if (null != httpClient)
				{
					httpClient.close();
				}
			} catch (IOException e)
			{
				
			}
		}
		
	}
	
	public void addUploadCarOutErrorLog(String businessUuid,String deScript)
	{
		Log logInfo = new Log();
		logInfo.setCreaterAt(new Date());
		logInfo.setSummary("上报出场异常.");
		logInfo.setDescript(deScript);
		logInfo.setLevel(LogInfoConstan.LEVEL_ALERT);
		logInfo.setSrc(LogInfoConstan.SRC_SYSTEM);
		logInfo.setStatus(LogInfoConstan.STATUS_UNTREATED);
		logInfo.setCls("com.cloud.threads.UpLoadCarOutInfoRunble");
		logInfo.setModule(LogInfoConstan.MODULE_CAR_OUT);
		logInfo.setBusinessUuid(businessUuid);
		logServier.addLogInfo(logInfo);
	}
}
